# 构建阶段1：系统依赖
FROM python:3.9-slim-bookworm AS system-deps

# 设置工作目录和环境变量
WORKDIR /build
ENV DEBIAN_FRONTEND=noninteractive \
    PIP_NO_CACHE_DIR=1 \
    PIP_DISABLE_PIP_VERSION_CHECK=1

# 使用阿里云apt源并安装构建依赖
RUN sed -i 's/deb.debian.org/mirrors.aliyun.com/g' /etc/apt/sources.list.d/debian.sources \
    && rm -rf /var/lib/apt/lists/* \
    && apt-get update \
    && apt-get install -y --no-install-recommends gcc python3-dev \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/*

# 构建阶段2：Python依赖
FROM system-deps AS builder

# 复制依赖文件并安装Python依赖
COPY requirements.txt .
RUN --mount=type=cache,target=/root/.cache/pip \
    pip install -i https://mirrors.aliyun.com/pypi/simple/ \
    --trusted-host mirrors.aliyun.com \
    --prefix=/install \
    --no-warn-script-location \
    -r requirements.txt

# 运行阶段：最终镜像
FROM python:3.9-slim-bookworm

# 设置工作目录和环境变量
WORKDIR /app
ENV PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1 \
    PYTHONPATH=/app

# 复制构建阶段安装的依赖
COPY --from=builder /install /usr/local

# 创建非root用户
RUN groupadd -r appgroup && useradd -r -g appgroup appuser \
    && mkdir -p /app/static \
    && chown -R appuser:appgroup /app

# 切换到非root用户
USER appuser

# 复制应用文件
COPY --chown=appuser:appgroup main.py healthcheck.py ./
COPY --chown=appuser:appgroup static/ static/

# 健康检查
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
    CMD python healthcheck.py

# 启动命令
CMD ["python", "-m", "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8001"]